package com.imu.wys.controller;


import com.alibaba.fastjson.JSONObject;
import com.imu.wys.model.Course;
import com.imu.wys.service.CourseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller("CourseController")
@RequestMapping(value = {"/course"})
public class CourseController {

    @Autowired
    CourseService courseService;

//    String filePath = "H:\\test";
    String filePath = "/usr/lib/soft/tomact/tomact/webapps";
    String pan = "D:";
    String fileWin = "D:\\04MyNewWorkspace\\HBuilderWork\\Spring-Boot\\webCount\\upCourse";
    @RequestMapping("uploadWin")
    public void uploadWin(@RequestParam("uploadfile") MultipartFile file, String cname, HttpServletRequest request, HttpServletResponse response) throws IllegalStateException, IOException, InterruptedException {
        response.setHeader("Access-Control-Allow-Origin", request.getHeader("origin"));
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS");
        response.setHeader("Access-Control-Allow-Headers", "Authorization,Origin, X-Requested-With, Content-Type, Accept,Access-Token");
        response.setCharacterEncoding("UTF-8");

        if(!file.isEmpty()) {//上传文件路径
            String path=fileWin; //如果写绝对路径可用这个path覆盖上边
            Course course = new Course();
            course.setCname(cname);
            courseService.addCourse(course);
            int cid = course.getCid();
            String cnum;
            if(cid<10){
                cnum= "00"+cid;
            }else if(cid<100){
                cnum= "0"+cid;
            }else {
                cnum = ""+cid;
            }
            course.setCnum(cnum);
            //上传文件名

            String filename = file.getOriginalFilename();
            String curl = path + File.separator + filename;
            course.setCurl(curl);
            File filepath = new File(path,filename);
            //判断路径是否存在，如果不存在就创建一个
            if (!filepath.getParentFile().exists()) {
                filepath.getParentFile().mkdirs();
            }
            //将上传文件保存到一个目标文件当中
            file.transferTo(new File(path + File.separator + filename));

            course.setCurl(path + File.separator + cnum);

            courseService.updateByID(course);

            String command0 = "" +pan;
            String command1 = "cd " +fileWin;
            String command2 = "unzip -o " +  filename;
            String command3 = "rename " +filename.split("\\.")[0] +" "+cnum;
            String command4 = "del " + filename;
            File util =new File("util.bat");
            if(!util.exists()){
                util.createNewFile();
            }
            FileWriter fileWritter = new FileWriter(util.getName(),false);
            BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
            bufferWritter.write("@echo no\n");
            bufferWritter.write(command0+"\n");
            bufferWritter.write(command1+"\n");
            bufferWritter.write(command2+"\n");
            bufferWritter.write(command3+"\n");
            bufferWritter.write(command4+"\n");

            bufferWritter.close();
            System.out.println("Done \n "+command1+"\n"+command2+"\n"+command3+"\n"+command4);
            Process child = Runtime.getRuntime().exec("util.bat");
            InputStream in = child.getInputStream();
            int c;
            in.close();
            try {
                child.waitFor();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            response.getWriter().print("上传成功"+String.valueOf(file.getSize()));
        }else {
            response.getWriter().print("上传失败");
        }
    }



    @RequestMapping("uploadLinux")
    public void testupload(@RequestParam("uploadfile") MultipartFile file, String cname, double price , HttpServletRequest request, HttpServletResponse response) throws IllegalStateException, IOException, InterruptedException {
        response.setHeader("Access-Control-Allow-Origin", request.getHeader("origin"));
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS");

        response.setHeader("Access-Control-Allow-Headers", "Authorization,Origin, X-Requested-With, Content-Type, Accept,Access-Token");
        response.setCharacterEncoding("UTF-8");
        if(!file.isEmpty()) {//上传文件路径
            String path=filePath; //如果写绝对路径可用这个path覆盖上边
            Course course = new Course();
            course.setCname(cname);
            courseService.addCourse(course);
            int cid = course.getCid();
            String cnum;
            if(cid<10){
                cnum= "00"+cid;
            }else if(cid<100){
                cnum= "0"+cid;
            }else {
                cnum = ""+cid;
            }
            course.setCnum(cnum);
            //上传文件名

            String filename = file.getOriginalFilename();
            course.setCurl(path + File.separator + filename);
            File filepath = new File(path,filename);
            //判断路径是否存在，如果不存在就创建一个
            if (!filepath.getParentFile().exists()) {
                filepath.getParentFile().mkdirs();
            }
            //将上传文件保存到一个目标文件当中
            file.transferTo(new File(path + File.separator + filename));

            course.setCurl(path + File.separator + cnum);

            courseService.updateByID(course);

            String command1 = "cd " +filePath;
            String command2 = "unzip " +filename;
            String command3 = "mv " +filename.split("\\.")[0] +" "+cnum;
            String command4 = "rm -rf " + filename;
            File util =new File("util.sh");
            if(!util.exists()){
                util.createNewFile();
            }
            FileWriter fileWritter = new FileWriter(util.getName(),false);
            BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
            bufferWritter.write("#! /bin/bash\n");
            bufferWritter.write(command1+"\n");
            bufferWritter.write(command2+"\n");
            bufferWritter.write(command3+"\n");
            bufferWritter.write(command4+"\n");
            bufferWritter.close();
            System.out.println("Done \n "+command1+"\n"+command2+"\n"+command3+"\n"+command4);
            Runtime.getRuntime().exec("bash  util.sh").waitFor();
            response.getWriter().print("上传成功"+String.valueOf(file.getSize()));
        }else {
            response.getWriter().print("上传失败");
        }
    }

    @RequestMapping("getAll")
    public void getAll(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setHeader("Access-Control-Allow-Origin", request.getHeader("origin"));
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS");
        response.setHeader("Access-Control-Allow-Headers", "Authorization,Origin, X-Requested-With, Content-Type, Accept,Access-Token");
        response.setCharacterEncoding("UTF-8");
        List<Course> courseList = courseService.getAll();
        Map<String, Object> map = new HashMap<>();
        map.put("code",200);
        map.put("courseList",courseList);

        JSONObject json = new JSONObject(map);
        response.getWriter().print(json.toString());


    }



}
